﻿using LBSoft.Business;
using LBSoft.Common.DotNetBean;
using LBSoft.Common.DotNetCode;
using LBSoft.Common.DotNetData;
using LBSoft.Common.DotNetExt;
using LBSoft.Common.DotNetJson;
using LBSoft.Common.DotNetUI;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;

namespace LBSoft.HplusAdmin.Business.Notice
{
    /// <summary>
    /// Notice 的摘要说明
    /// </summary>
    public class Notice : IHttpHandler
    {
        HttpContext con = null;
        mJsonResult json = new mJsonResult();
        Common_Dal systemidao = new Common_Dal();
        LogHelper log = new LogHelper();

        public void ProcessRequest(HttpContext context)
        {
            con = context;

            switch (con.Request["PostType"])
            {
                case "list": LoadList(); break;
                case "get": GetData(); break;
                case "set": SetData(); break;
                case "del": DelData(); break;
            }
        }

        #region 列表
        private void LoadList()
        {
            switch (con.Request["ActionType"])
            {
                case "Notice": LoadNoticeList(); break; //通知信息列表
                case "UnReadNotice": LoadUnReadNoticeList(); break; //未读消息列表
            }
        }

        /// <summary>
        /// 通知信息列表
        /// </summary>
        private void LoadNoticeList()
        {
            int count = 0;
            int pageSize = con.Request["rows"].ToInt32(15);
            int curPage = con.Request["page"].ToInt32(1);

            IList<SqlParam> IList_param = new List<SqlParam>();
            StringBuilder SqlWhere = new StringBuilder(WebHelper.GetCondition(con.Request));
            SqlWhere.Append(" AND a.IsDelete=0 ");

            string tables = @" T_Notice a ";
            string cols = @" a.* ";
            string orderStr = " CreateDate Desc ";

            DataTable dt = systemidao.GetListByPage(tables, cols, SqlWhere, orderStr, IList_param, curPage, pageSize, ref count);

            json.success = true;
            json.total = count;
            json.rows = dt;

            con.Response.Write(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 未读消息列表
        /// </summary>
        private void LoadUnReadNoticeList()
        {
            int count = 0;
            int pageSize = con.Request["rows"].ToInt32(15);
            int curPage = con.Request["page"].ToInt32(1);
            string userId = RequestSession.GetSessionUser().UserId;

            IList<SqlParam> IList_param = new List<SqlParam>();
            StringBuilder SqlWhere = new StringBuilder(WebHelper.GetCondition(con.Request));

            string tables = string.Format(@" (SELECT * FROM dbo.T_Notice
            WHERE IsDelete=0 AND NOT EXISTS(
            SELECT NGUID FROM dbo.T_NoticeReadRecord WHERE UGUID='{0}' AND NGUID=Guid)) n ", userId);

            string searchType = con.Request["searchType"].ToString2();
            if (!string.IsNullOrEmpty(searchType))
            {
                if (searchType == "1")
                {
                    tables = string.Format(@" (SELECT * FROM dbo.T_Notice
                    WHERE EXISTS(
                    SELECT NGUID FROM dbo.T_NoticeReadRecord WHERE UGUID='{0}' AND NGUID=Guid)) n ", userId);
                }
                else if (searchType == "2")
                {
                    tables = @" T_Notice n ";
                }
            }

            string cols = @" n.*";
            string orderStr = " PublishDate desc ";

            DataTable dt = systemidao.GetListByPage(tables, cols, SqlWhere, orderStr, IList_param, curPage, pageSize, ref count);
            json.success = true;
            json.total = count;
            json.rows = dt;
            string strJson = JsonConvert.SerializeObject(json);
            con.Response.Write(strJson);
        }
        #endregion

        #region 获取
        private void GetData()
        {
            switch (con.Request["ActionType"])
            {
                case "Notice": GetNotice(); break; //获取通知信息
                case "UnReadNoticeInfo": GetUnReadNoticeInfo(); break; //获取首页未读消息
            }
        }

        /// <summary>
        /// 获取通知信息
        /// </summary>
        private void GetNotice()
        {
            string guid = con.Request["GUID"].ToString2();

            Hashtable ht = systemidao.GetDataByID("T_Notice", "GUID", guid);

            con.Response.Write(JsonConvert.SerializeObject(ht));
        }

        /// <summary>
        /// 获取首页未读消息
        /// </summary>
        private void GetUnReadNoticeInfo()
        {
            string userId = RequestSession.GetSessionUser().UserId;
            int userType = RequestSession.GetSessionUser().UserType;

            int unReadNoticeNum = 0;

            //if (userType != 1)
            //{
            unReadNoticeNum = systemidao.ExecuteScalar($@"SELECT COUNT(0) cCount FROM dbo.T_Notice 
                WHERE IsDelete=0 AND NOT EXISTS(SELECT NGUID FROM dbo.T_NoticeReadRecord WHERE UGUID='{userId}' AND NGUID=GUID)").ToInt32();
            //}

            //只查前5条未读消息
            //DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($@"
            //SELECT TOP 5 * FROM dbo.T_Notice 
            //WHERE IsDelete=0 AND NOT EXISTS(SELECT NGUID FROM dbo.T_NoticeReadRecord WHERE UGUID='{userId}' AND NGUID=GUID)
            //ORDER BY PublishDate desc"));

            DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($@"
            SELECT TOP 10 a.* FROM (
	            SELECT n.*
	            ,CASE WHEN ISNULL(nr.NGUID,'')='' THEN 0 ELSE 1 END IsRead
	            FROM dbo.T_Notice n
	            LEFT JOIN dbo.T_NoticeReadRecord nr ON nr.NGUID=n.GUID AND nr.UGUID='{userId}'
            ) a
            ORDER BY a.IsRead ASC"));

            json.success = true;
            json.rows = dt;
            json.total = unReadNoticeNum;

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region  编辑
        private void SetData()
        {
            switch (con.Request["ActionType"])
            {
                case "Notice": SetNotice(); break; //通知信息保存
                case "ReadNotice": SetReadNotice(); break;  //设置消息已读，新增T_NoticeReadRecord记录
            }
        }

        /// <summary>
        /// 通知信息保存
        /// </summary>
        private void SetNotice()
        {
            try
            {
                string userId = RequestSession.GetSessionUser().UserId;
                string userAccount = RequestSession.GetSessionUser().UserAccount;

                string guid = con.Request["GUID"].ToString2();

                Hashtable ht = systemidao.AddHashtable("T_Notice", con);

                if (string.IsNullOrEmpty(guid))
                {
                    ht["IsDelete"] = 0;
                    ht["CreateDate"] = DateTime.Now;
                    ht["CreateUserId"] = userId;
                    ht["CreateAccount"] = userAccount;
                }
                else
                {
                    ht.Remove("IsDelete");
                    ht.Remove("CreateDate");
                    ht.Remove("CreateUserId");
                    ht.Remove("CreateAccount");
                    ht["ModifyDate"] = DateTime.Now;
                    ht["ModifyUserId"] = userId;
                    ht["ModifyAccount"] = userAccount;
                }

                bool result = systemidao.SubmitData("T_Notice", "GUID", guid, ht);
                json.success = result;

                if (result)
                {
                    json.msg = "保存成功！";
                }
                else
                {
                    json.msg = "保存失败！";
                }
            }
            catch (Exception ex)
            {
                json.msg = ex.Message;
                log.WriteExceptionLog(ex);
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 设置消息已读
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void SetReadNotice()
        {
            string guid = con.Request["GUID"].ToString2();
            string userId = RequestSession.GetSessionUser().UserId;

            int count = systemidao.ExecuteScalar($@"SELECT COUNT(1) FROM dbo.T_NoticeReadRecord WHERE NGUID='{guid}' AND UGUID='{userId}'").ToInt32();
            if (count == 0)
            {
                json.success = systemidao.ExecuteBySql(new StringBuilder($@"
                INSERT INTO dbo.T_NoticeReadRecord (NGUID,UGUID,ReadDate) VALUES ('{guid}','{userId}','{DateTime.Now}')")) > 0 ? true : false;
            }
            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 删除
        private void DelData()
        {
            switch (con.Request["ActionType"])
            {
                case "Notice": DelNotice(); break; //通知信息删除
            }
        }

        /// <summary>
        /// 通知信息删除
        /// </summary>
        private void DelNotice()
        {
            string guid = con.Request["GUID"].ToString2();

            if (string.IsNullOrEmpty(guid))
            {
                json.success = false;
                json.msg = "没有要删除的主键！";
                con.Response.Write(JsonConvert.SerializeObject(json));
                return;
            }

            List<string> list = guid.Split(',').ToList<string>();
            bool result = systemidao.BatchUpdateDeleteData("T_Notice", "GUID", list.ToArray()) > 0;
            json.success = result;

            if (result)
            {
                json.msg = "删除成功！";
            }
            else
            {
                json.msg = "删除失败！";
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}